package com.lagou.boot;

import com.lagou.*;
import com.lagou.handler.RpcHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author godai
 * @date 2021/1/31 13:41
 * @description
 */
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRunnerImpl.class);

    @Value("${rpc.port}")
    private int port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置解码
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));

                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new RpcHandler());
                    }
                });

        LOGGER.info("rpc start at:{}", port);
        //4.绑定端口
        serverBootstrap.bind(port).sync();
    }
}
